package com.easy.controller;

import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easy.bean.*;
import com.easy.service.*;
import com.easy.util.*;
import com.easy.exception.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    AdminService adminService;

    @RequestMapping("/dologin")
    public Result doLogin(Admin admin, @RequestParam("key") String key, @RequestParam("captcha") String code) {
        boolean flag = InnerCaptchaUtil.verifyCaptcha(key, code);
        if (!flag) {
            throw new ServiceException("验证码错误");
        }
        if (Util.isEmpty(admin.getPhone(), admin.getPassword())) {
            throw new ServiceException("数据格式错误");
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, admin.getPhone());
        Admin dbAdmin = adminService.getOne(queryWrapper);
        if (dbAdmin==null) {
            throw new ServiceException("用户名或密码错误");
        }
        flag=PasswordDecode.verify(admin.getPassword(), dbAdmin.getPassword());
        if (!flag) {
            throw new ServiceException("用户名或密码错误");
        }else{
            HashMap<String,Object> map = new HashMap<>();
            map.put(TokenUtil.USERID, dbAdmin.getId());
            map.put(TokenUtil.USERNAME, dbAdmin.getPhone());
            return Result.success(TokenUtil.generateToken(map));
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody Admin admin) {
        if(Util.isNull(admin.getPhone(), admin.getPassword())) {
            throw new ServiceException("数据格式错误");
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, admin.getPhone());
        Admin dbAdmin = adminService.getOne(queryWrapper);
        if(dbAdmin != null) {
//            return Result.error(400, "用户已存在");
            throw new ServiceException("用户已存在");
        }
        return Result.success(200, "注册成功",adminService.save(admin));
    }
     @GetMapping("/loginbean")
    public Result getLoginBean(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        NumberWithFormat payload = (NumberWithFormat) TokenUtil.getPayload(token, TokenUtil.USERID);
        Admin admin= adminService.getById( payload.intValue());
        return Result.success(200, "", admin);
    }
}
